package com.blfq.server;

import javax.swing.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.blfq.common.constant.Constants.*;

public class ChatClient {

    /**
     *  配置客户端的多线程操作数：一个用于接收服务器转发的信息，一个用于发生数据，
     *  思考：如果有更多功能，线程池应如何进行设置？
     *  思考：能否给客户端添加一个列表，显示在线的聊天用户
     *
     */
    private static ExecutorService pool = Executors.newFixedThreadPool(3);

    private JFrame frame;
    private JTextArea chatArea;
    private JTextField inputField;
    private PrintWriter out;

    private Socket socket;

    private BufferedReader in;
    private BufferedReader keyboard;

    public ChatClient() {
        createUI();
    }

    private void createUI() {
        frame = new JFrame(WINDOW_TITLE);
        chatArea = new JTextArea(20, 50);
        chatArea.setEditable(false);
        inputField = new JTextField(40);
        JButton sendButton = new JButton("发送");

        //需要同一行显示的，使用JPanel包含起来
        JPanel panel = new JPanel();
        panel.add(inputField);
        panel.add(sendButton);

        frame.getContentPane().add(new JScrollPane(chatArea), BorderLayout.CENTER);
        frame.getContentPane().add(panel, BorderLayout.SOUTH);

        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        //当点击发送按钮时，需要清空输入框，并发送数据到服务器
        //使用Lambda表达式简化代码
        sendButton.addActionListener(e -> sendMessage());
        inputField.addActionListener(e -> sendMessage());
    }

    private void sendMessage() {
        String message = inputField.getText().trim();
        if (!message.isEmpty()) {
            //发送到服务器
            out.println(message);
            //清空输入框
            inputField.setText("");
        }
    }

    public void start() {
        try {

            socket = new Socket(SERVER_ADDRESS, SERVER_PORT);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);
            keyboard = new BufferedReader(new InputStreamReader(System.in));

            // 输入用户名
            String name = JOptionPane.showInputDialog(frame, "请输入你的名称:");
            if(name == null){
                System.exit(0);
            }
            //发送登录账号到服务器
            out.println(name);

            // 接收服务器消息
            //使用lambda表达式实现Runnable接口，简化代码
            pool.execute(() -> {
                try {
                    String message;
                    //接收服务器转发的消息，注意接收信息和发送信息是不同的线程
                    while ((message = in.readLine()) != null) {
                        //把接收的聊天信息添加到列表中显示
                        chatArea.append(message + "\n");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            ChatClient client = new ChatClient();
            client.start();
        });
    }
}
